<?php

//运单控制器
class QuickTrainApp extends BackendApp
{
	var $_waybill_mod;
	var $_dictionary_mod;
	var $_user_mod;
	var $canedit;
	var $_haul_mod;
	function __construct()
	{
		$this->QuickTrainApp();
	}

	function QuickTrainApp()
	{
		parent::BackendApp();

		$this->_waybill_mod =& m('waybill');
		$this->_dictionary_mod =& m('dictionary');
		$this->_user_mod =& m('member');
		$this->_haul_mod =& m('haul');
		$this->canedit=false;
	}

	function index()
	{
		$db=&db();
		$types=array();
		$types['集港'] = '集港';
		$types['疏港'] = '疏港';

		$this->assign('types', $types);

		$status=array();
		$status['新建'] = '新建';
		$status['已派'] = '已派';
		$status['已接单'] = '已接单';

		$this->assign('status', $status);

		$wm_carrier=empty($_GET['wm_carrier'])?'':$_GET['wm_carrier'];
		$type_id=empty($_GET['type_id'])?'':$_GET['type_id'];
		$mstatus=empty($_GET['status'])?'':$_GET['status'];


		$conditions = "1=1 and (wm_type='集港' or wm_type='疏港') and (wm_stauts='新建' or wm_stauts='已接单' or wm_stauts='已派')";
		if($wm_carrier){
			$conditions.=" and wm_carrier LIKE '%".$wm_carrier."%'";
		}
		if($type_id){
			$conditions.="  AND wm_type ='".$type_id."'";
		}

		if($mstatus!=null&&$mstatus!=''){
			$conditions.=" and wm_stauts='".$mstatus."' ";
		}
		$user_ids = $this->checkpower();
		if(!empty($user_ids)){
			$conditions.=" and wm_optid in(".$user_ids.")";
		}
		$page   =   $this->_get_page(10);   //获取分页信息

		$sql2 = "SELECT distinct waybill_main.*,t.g_ship,t.g_voyage,t.g_awb_code,smember.real_name as sname,ifnull(waybill_main.wm_user,0) as wm_user,
		t.g_packingtime,t.g_collectiontime,
		g.g_box,w.ws_volume,t.g_container_depot,t.g_full_container_depot,member.user_name,waybill_main.wm_tid,t.g_loading_place
		FROM zys_waybill_main waybill_main 
		LEFT JOIN zys_member smember ON waybill_main.wm_user=smember.user_id
		LEFT JOIN zys_waybill_sub_trunk w ON waybill_main.wm_tid=w.ws_wmtid 
		LEFT JOIN zys_goods_trunk_sub g on w.ws_gstid=g.gs_tid
		LEFT JOIN zys_goods_trunk t on t.g_tid=g.gs_gtid 
		LEFT JOIN zys_member member ON waybill_main.wm_optid = member.user_id 
				WHERE  ".$conditions." ORDER BY wm_tid desc LIMIT ".$page['limit'];
		$waybill = $db->getAll($sql2);
		$sql3=" SELECT COUNT(*) FROM (SELECT DISTINCT  waybill_main.*,t.g_ship,t.g_voyage,t.g_awb_code,member.user_name
		FROM zys_waybill_main waybill_main 
		LEFT JOIN zys_waybill_sub_trunk w ON waybill_main.wm_tid=w.ws_wmtid 
		LEFT JOIN zys_goods_trunk_sub g on w.ws_gstid=g.gs_tid
		LEFT JOIN zys_goods_trunk t on t.g_tid=g.gs_gtid 
		LEFT JOIN zys_member member ON waybill_main.wm_optid = member.user_id 
		where $conditions
		GROUP BY waybill_main.wm_tid  ) AA   ";

		$page['item_count']=$db->getOne($sql3);   //获取统计数据

		$this->_format_page($page);

		$this->assign('page_info', $page);   //将分页信息传递给视图，用于形成分页条
		$this->assign('waybill', $waybill);
		$this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));

		$this->assign('tabself', json_encode(array('text'=>'运单管理')));
		$this->display('quicktrain.index.html');
	}


	//车牌号列表
	function choose()
	{
		$db=&db();

		$oper_id=$_GET['oper'];

		$this->assign('oper', $oper_id);

		if(empty($oper_id)){
			$oper_id=$_POST['oper'];
			$this->assign('oper', $oper_id);
		}

		$conditions = $this->_get_query_conditions(array(
		array(
				'field' => $_GET['field_name'],
				'name'  => 'field_value',
				'equal' => 'like',
		),
		));
		//更新排序
		if (isset($_GET['sort']) && !empty($_GET['order']))
		{
			$sort  = strtolower(trim($_GET['sort']));
			$order = strtolower(trim($_GET['order']));
			if (!in_array($order,array('asc','desc')))
			{
				$sort  = 'last_login';
				$order = 'desc';
			}
		}
		else
		{
			if (isset($_GET['sort']) && empty($_GET['order']))
			{
				$sort  = strtolower(trim($_GET['sort']));
				$order = "";
			}
			else
			{
				$sort  = 'last_login';
				$order = 'desc';
			}
		}
		$page = $this->_get_page();

		$sql="SELECT * FROM zys_authoperator a LEFT JOIN zys_member m ON a.zao_usertid=m.user_id
			WHERE a.zao_authed=1 AND ifnull(m.type,0)<>0 ". $conditions." order by $sort $order limit $page[limit]";
		$users =$db->getAll($sql);

		$sql="SELECT COUNT(1) FROM zys_authoperator a LEFT JOIN zys_member m ON a.zao_usertid=m.user_id
			WHERE  a.zao_authed=1 AND ifnull(m.type,0)<>0 ". $conditions;
		$page['item_count']  =$db->getOne($sql);

		foreach ($users as $key => $val)
		{
			if ($val['priv_store_id'] == 0 && $val['privs'] != '')
			{
				$users[$key]['if_admin'] = true;
			}
		}
		$this->assign('users', $users);
		$this->assign('wid', $_GET['wid']);
		$page['item_count'] = $this->_user_mod->getCount();
		$this->_format_page($page);
		$this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
		$this->assign('page_info', $page);
		$this->assign('query_fields', array(
			'vhcCode' => '车牌号',
			'real_name'     => '司机',
			'phone_tel' => '手机号',
		//            'phone_tel' => LANG::get('phone_tel'),
		//            'phone_mob' => LANG::get('phone_mob'),
		));

		$this->display('quicktrain.choose.html');
	}

	function choosedone() {
		$oid=empty($_GET['id'])?0:intval($_GET['id']);
		$wid=empty($_GET['wid'])?0:intval($_GET['wid']);
		$oper=empty($_GET['oper'])?0:intval($_GET['oper']);
		$db=&db();

		$name="";
		$uid=0;
		$sql="SELECT m.real_name,a.zao_usertid FROM zys_authoperator a LEFT JOIN zys_member m ON a.zao_usertid=m.user_id
			WHERE zao_tid=$oid AND zao_authed=1 AND ifnull(m.type,0)<>0";
		$row=$db->getRow($sql);
		$name =$row['real_name'];
		$uid=$row['zao_usertid'];
		if(empty($uid)){
			$this->show_warning('司机不存在','',    'index.php?app=quicktrain');
			return ;
		}

		echo("<script>window.parent.change($uid,'".$name."',$wid);</script>");
	}

	function alltrain(){

		$db=&db();
		$arrs = isset($_POST['sj']) ? $_POST['sj'] : '';
		$arrsop = isset($_POST['op']) ? $_POST['op'] : '';
		$checkarrs = isset($_POST['cnum']) ? $_POST['cnum'] : '';

		if($checkarrs!=null&&count($checkarrs)>0){
			foreach ($checkarrs as $k=>$v){

				$sql="select * from zys_member where user_id=".$arrs[$k];
				$user=$db->getRow($sql);

				$sql="SELECT o_name from zys_operator WHERE o_tid=".$arrsop[$k];
				$oname=$db->getOne($sql);

				if(!$oname){
					$sql="SELECT o.o_name FROM zys_authoperator a LEFT JOIN zys_operator o ON o.o_tid=a.zao_otid
					WHERE zao_usertid=$arrs[$k] AND zao_authed=1 ORDER BY zao_auth_date DESC LIMIT 1";
					$oname=$db->getOne($sql);
				}

				if($user){
					$sql="update zys_waybill_main set wm_user='".$arrs[$k]."',wm_uuid='".$user['uuid']."',wm_dispatch_date='".gmtime()."',wm_dispatch_person='".$this->visitor->get('user_name')."',
					wm_dispatch_person_tel='".$this->visitor->get('phone_tel')."',wm_vhc_code='".$user['vhcCode']."',wm_driver='".$user['real_name']."'
					,wm_driver_tel='".$user['phone_tel']."',wm_carrier='".$oname."',wm_carrier_id=$arrsop[$k] where wm_tid=".$k;
					$db->query($sql);
				}


				//派车
				$sql="select * from zys_waybill_main where wm_tid=".$k;
				$w=$db->getRow($sql);

				if(!empty($k)){
					//修改运单状态
					$sql="UPDATE zys_waybill_main SET wm_stauts='已派' WHERE wm_tid=$k";
					$db->query($sql);

					//修改运单信息
					$sql="UPDATE zys_waybill_main SET wm_uuid='".$user['uuid']."' WHERE wm_tid=$k";
					$db->query($sql);


					//发送推送消息
					require_once ROOT_PATH.'/baidupush/sdk.php';
					$sdk = new PushSDK();
					$channelId = $user['channelId']?$user['channelId']:'3849309310203392735';
					try{

						$opts = array (
							'msg_type' => 0
						);
						if($w['wm_type']=='疏港 ') {
							$sql="select * from zys_goods_trunk where exists(select 1 from zys_waybill_sub_trunk where g_tid=ws_gid and ws_wmtid=".$k.")";
							$gt=$db->getRow($sql);

							$rs = $sdk->pushMsgToSingleDevice($channelId,
							'{"type":"3","result":{"wm_tid":"' . $k . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_collectiontime']) . '到' . $gt['g_full_container_depot'] . '背重箱
							' . local_date('Y年m月d日 H点i分', $gt['g_packingtime']) . '送至' . $gt['g_loading_place'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
						}else if($w['wm_type']=='集港 ') {
							$sql="select * from zys_goods_trunk where exists(select 1 from zys_waybill_sub_trunk where g_tid=ws_gid and ws_wmtid=".$wid.")";
							$gt=$db->getRow($sql);

							$rs = $sdk->pushMsgToSingleDevice($channelId,
							'{"type":"3","result":{"wm_tid":"' . $k . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_packingtime']) . '到' . $gt['g_loading_place'] . '装货
							' . local_date('Y年m月d日 H点i分', $gt['g_collectiontime']) . '前送至' . $gt['g_full_container_depot'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
						}else {
							$rs = $sdk->pushMsgToSingleDevice($channelId,
							'{"type":"3","result":{"wm_tid":"' . $k . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $w['wm_loading_date']) . '到' . $w['wm_loading_place'] . '提货
							' . local_date('Y年m月d日 H点i分', $w['wm_required_service_date']) . '送至' . $w['wm_unloading_place'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
						}
					}catch (Exception $ex){

					}
				}


			}
		}
		$this->show_message('发车成功','', 'index.php?app=quicktrain');

	}


	/**
	 * 派车处理
	 */
	function paichedone() {
		$db=&db();
		$wid=empty($_GET['wm_tid'])?0:intval($_GET['wm_tid']);
		$uid=empty($_GET['wm_user'])?0:intval($_GET['wm_user']);

		$sql="select * from zys_waybill_main where wm_tid=".$wid;
		$w=$db->getRow($sql);

		$sql="select * from zys_member where user_id=".$uid;
		$user=$db->getRow($sql);
		if(!empty($wid)){
			//修改运单状态
			$sql="UPDATE zys_waybill_main SET wm_stauts='已派' WHERE wm_tid=$wid";
			$db->query($sql);

			//修改运单信息
			$sql="UPDATE zys_waybill_main SET wm_uuid='".$user['uuid']."' WHERE wm_tid=$wid";
			$db->query($sql);


			//发送推送消息
			require_once ROOT_PATH.'/baidupush/sdk.php';
			$sdk = new PushSDK();
			$channelId = $user['channelId']?$user['channelId']:'3849309310203392735';
			try{

				$opts = array (
				'msg_type' => 0
				);
				if($w['wm_type']=='集卡进口 ') {
					$sql="select * from zys_goods_trunk where exists(select 1 from zys_waybill_sub_trunk where g_tid=ws_gid and ws_wmtid=".$wid.")";
					$gt=$db->getRow($sql);

					$rs = $sdk->pushMsgToSingleDevice($channelId,
						'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_collectiontime']) . '到' . $gt['g_full_container_depot'] . '背重箱
				' . local_date('Y年m月d日 H点i分', $gt['g_packingtime']) . '送至' . $gt['g_loading_place'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
				}
				else if($w['wm_type']=='集卡出口 ') {
					$sql="select * from zys_goods_trunk where exists(select 1 from zys_waybill_sub_trunk where g_tid=ws_gid and ws_wmtid=".$wid.")";
					$gt=$db->getRow($sql);

					$rs = $sdk->pushMsgToSingleDevice($channelId,
						'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_packingtime']) . '到' . $gt['g_loading_place'] . '装货
				' . local_date('Y年m月d日 H点i分', $gt['g_collectiontime']) . '前送至' . $gt['g_full_container_depot'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
				}
				else {
					$rs = $sdk->pushMsgToSingleDevice($channelId,
						'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $w['wm_loading_date']) . '到' . $w['wm_loading_place'] . '提货
				' . local_date('Y年m月d日 H点i分', $w['wm_required_service_date']) . '送至' . $w['wm_unloading_place'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
				}
			}catch (Exception $ex){

			}
		}

		$this->show_message('派车成功',
                '返回运单',   'index.php?app=waybill&act=edit&id=' . $wid
		);

	}


	//判断权限
	/*function checkpower(){
		$db = &db();
		$user = $this->visitor->get();
		if($user['type'] >0){
		if($user['subtype']==1 || $user['subtype']==0 && $user['giveauth']==1){
		//看到他单位的
		$unit = $user['unit'];
		$sql = "select  group_concat(Convert(user_id , char)) from zys_member where unit=".$unit;
		$user_ids = $db->getOne($sql);
		}else{
		$user_ids = $user['user_id'];
		}
		}
		return $user_ids;
		}*/
}